<script setup>
import {ref, inject} from 'vue'
import {getUserByUsername, getUserInfo, userLogin} from "@/res/api/user_api.js"
import {
  ArrowUndoOutline as BackIcon,
  CallOutline as PhoneIcon,
  MailOutline as EmailIcon,
  PersonSharp as UserIcon,
  DesktopSharp as AdminIcon
} from "@vicons/ionicons5"
const {toPage} = inject('toPage')
const loginRef = ref(null);
//用户信息
const user = ref({
  uname:null,
  password:null
})
//测试用户
const admin = ref({
  order:'353762489',
  headerImg:'https://picsum.photos/seed/picsum/200/300',
  nickName:"王大锤",
  username:'1212567',
  password:'123456',
  name:'小明',
  sex:'男',
  age:'25',
  rule: 'student',
})

const token=ref(String('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjpbeyJvcmRlciI6IjM1Mzc2MjQ4OSJ9LHsiaGVhZGVySW1nIjoiaHR0cHM6Ly9waWNzdW0ucGhvdG9zL3NlZWQvcGljc3VtLzIwMC8zMDAifSx7Im5pY2tuYW1lIjoi546L5aSn6ZSkIn0seyJ1c2VybmFtZSI6IjEyMTI1NjcifSx7Im5hbWUiOiLlsI_mmI4ifSx7InNleCI6IueUtyJ9LHsiYWdlIjoiMjEifSx7InJ1bGUiOiJhZG1pbiJ9XSwiaWF0IjoxNzEzNTE4NjE1LCJleHAiOjE3NDU5NDIzOTksImF1ZCI6IiIsImlzcyI6IiIsInN1YiI6IiJ9._yA3HgFU_GEY6buKkTCfaLX0UMibhkktzS59WpCYwnc'))

//校验规则
const rules = {
  uname:{
    required:true,
    validator(rule, value){
      if(!value){
        return new Error("请输入账户")
      } else if (value.length<3){
        return new Error("账户至少为3位数")
      }
    },
    trigger: ['input','blur']
  },
  password:{
    required:true,
    validator(rule, value){
      if(!value){
        return new Error("请输入密码")
      } else if (value.length<6){
        return new Error("密码至少为六位数")
      }
    },
    trigger: ['input','blur']
  }
}
//校验登录
function handleValidateClick(e) {
  e.preventDefault();
  loginRef.value?.validate((errors) => {
    if (!errors) {
       userLogin({
        username: user.value.uname,
        password: user.value.password
      }).then((res)=>{
        if (res.data){
          sessionStorage.setItem('Authorization','Bearer\xa0'+res.data)
          // 解析token获得用户信息 -> 跳转到学习中心总览
          getUserInfoHome()
        }
        else {
          $message.destroyAll()
          $message.error("账户无效");
        }
      }).catch((err)=>{
        console.log(err)
      })
    } else {
      $message.destroyAll()
      $message.error("校验识别，请检测账户名/密码是否正确");
    }
  });
}
//获取用户信息
function getUserInfoHome(){
  getUserInfo().then(res => {
    sessionStorage.setItem("user", JSON.stringify(res.data))
    $message.success("登录成功");
    toPage('std/learn')
  })
}
//不同登录方式
let placeholderName = "请输入账户"
function msg(str) {
  placeholderName = str
  $message.destroyAll()
  $message.info(placeholderName)
}
</script>

<template>
<n-flex justify="center" align="center" class="login">
  <n-flex justify="space-between" class="login-body">
    <div class="login-img"/>
    <div class="login-form">
      <n-space justify="end" :style="{margin:'.5rem 0'}">
        <n-icon @click="toPage()" class="hover-pointer"><BackIcon/></n-icon>
      </n-space>
      <n-form ref="loginRef" :model="user" :rules="rules">
        <n-form-item path="uname" label="账户">
          <n-input type="text" v-model:value="user.uname" maxlength="21" :placeholder="placeholderName"/>
        </n-form-item>
        <n-form-item path="password" label="密码">
          <n-input type="password"
                   v-model:value="user.password"
                   placeholder="请输入密码"
                   maxlength="16"
                   show-password-on="mousedown"
                   @keyup.enter="handleValidateClick"
          />
        </n-form-item>
      </n-form>
      <n-button type="info" block strong @click="handleValidateClick">登录</n-button>
      <n-space :style="{margin:'20px 0'}" justify="space-evenly">
        <n-float-button shape="square" position="relative" @click="msg('请输入账户')">
          <n-icon><UserIcon/></n-icon>
        </n-float-button>
        <n-float-button shape="square" position="relative" @click="msg('请输入电话')">
          <n-icon><PhoneIcon/></n-icon>
        </n-float-button>
        <n-float-button shape="square" position="relative" @click="msg('请输入邮箱')">
          <n-icon><EmailIcon/></n-icon>
        </n-float-button>
        <n-float-button shape="square" position="relative" @click="toPage('admin/login')" title="管理员登录">
          <n-icon><AdminIcon/></n-icon>
        </n-float-button>
      </n-space>
      <n-space justify="space-between">
        <n-button type="info" block dashed @click="toPage()">取消</n-button>
        <n-button type="info" block dashed @click="toPage('forgot')">忘记密码</n-button>
        <n-button type="info" block dashed @click="toPage('register')">注册</n-button>
      </n-space>
    </div>
  </n-flex>
</n-flex>
</template>

<style lang="scss" scoped>
.login{
  width: 100%;
  height: 100vh;
}
.login-body{
  padding: 0;
  position: relative;
  width: 64vw;
  height: 54vh;
  box-shadow: 2px 2px 12px 2px #f5f5f5 inset;
  /* 指定动画 */
  animation-name: testKey;
  /* 设置动画所需时间 */
  animation-duration: 5s;
  /* 设置动画延迟 */
  animation-delay: 0.5s;
  .login-img{
    display: inline-block;
    position: relative;
    width: 45%;
    height: 100%;
    background: url("/src/assets/picture/loginBg.png");
    background-size: 100% 100%;
  }
  .login-form{
    display: inline-block;
    position: absolute;
    top: 0;
    right: 0;
    width: 47%;
    height: 100%;
    margin: 0 4%;
    @media screen and (max-width:768px) {
      /*CSS-Code;*/
      .login-form{
        width: 42%;
        height: 72%;
        margin: 0 2%;
      }
    }
    @media screen and (min-width:768px) and (max-width:1200px) {
      /*CSS-Code;*/
      .login-form{
        width: 42%;
        height: 81%;
        margin: 0 3%;
      }
    }
  }
}

</style>
